package com.tiger.cloud.filter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.context.ServletContextAware;

import com.tiger.cloud.dao.system.SysScheduleJobDao;
import com.tiger.cloud.model.system.SysScheduleJob;
import com.tiger.cloud.service.system.ISysScheduleJobService;

/**
 * @description: 初始化
 */
public class QuartzInitializationListener implements ServletContextAware, ApplicationListener<ContextRefreshedEvent> {

	private ServletContext servletContext;
	@Autowired
	private SysScheduleJobDao scheduleJobDao;
	@Autowired
	private ISysScheduleJobService jobTaskService;

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
		if (servletContext != null && contextRefreshedEvent.getApplicationContext().getParent() == null) {
			System.out.println("----InitializationListener-----开始初始化SPRING和TOMCAT容器---------");
			Map<String,Object> params=new HashMap<String, Object>();
			params.put("jobType", "1");
			List<SysScheduleJob> scheduleJobs = scheduleJobDao.find(params);
			if (scheduleJobs != null) {
				List<String> idsList=new ArrayList<String>();
				for (SysScheduleJob scheduleJob : scheduleJobs) {
					try {
						System.out.println("--添加任务--JobName--[" + scheduleJob.getJobName() + "]");
						jobTaskService.addJob(scheduleJob);
						idsList.add(scheduleJob.getId());
					} catch (SchedulerException e) {
						e.printStackTrace();
					}
				}
			}
			System.out.println("----InitializationListener-----完成初始化SPRING和TOMCAT容器---------");
		}
	}
}